package com.szz.cardecision.controller;

import com.szz.cardecision.entity.Gift;
import com.szz.cardecision.entity.GiftRedemption;
import com.szz.cardecision.entity.PointsTransaction;
import com.szz.cardecision.entity.User;
import com.szz.cardecision.mapper.GiftMapper;
import com.szz.cardecision.mapper.GiftRedemptionMapper;
import com.szz.cardecision.mapper.PointsTransactionMapper;
import com.szz.cardecision.mapper.UserMapper;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.LocalDateTime;
import java.util.List;

@Controller
public class PointsController {
    private final UserMapper userMapper;
    private final GiftMapper giftMapper;
    private final GiftRedemptionMapper giftRedemptionMapper;
    private final PointsTransactionMapper pointsTransactionMapper;

    public PointsController(UserMapper userMapper, GiftMapper giftMapper, GiftRedemptionMapper giftRedemptionMapper, PointsTransactionMapper pointsTransactionMapper) {
        this.userMapper = userMapper;
        this.giftMapper = giftMapper;
        this.giftRedemptionMapper = giftRedemptionMapper;
        this.pointsTransactionMapper = pointsTransactionMapper;
    }

    @GetMapping("/points")
    public String pointsPage(Authentication auth, Model model) {
        User user = userMapper.findByUsername(auth.getName()).orElseThrow();
        List<Gift> gifts = giftMapper.findAllActive();
        List<PointsTransaction> txs = pointsTransactionMapper.findByUserId(user.getId());
        model.addAttribute("user", user);
        model.addAttribute("gifts", gifts);
        model.addAttribute("txs", txs);
        return "points";
    }

    @PostMapping("/redeem/{giftId}")
    public String redeem(@PathVariable Long giftId, Authentication auth, Model model) {
        User user = userMapper.findByUsername(auth.getName()).orElseThrow();
        Gift gift = giftMapper.findById(giftId).orElseThrow();

        if (gift.getCostPoints() > (user.getPoints() == null ? 0 : user.getPoints())) {
            model.addAttribute("error", "积分不足，无法兑换该礼品。");
            return "redirect:/points";
        }

        // decrease user points and create transaction
        user.setPoints(user.getPoints() - gift.getCostPoints());
        userMapper.update(user);
        PointsTransaction tx = new PointsTransaction();
        tx.setUserId(user.getId());
        tx.setChangeAmount(-gift.getCostPoints());
        tx.setReason("兑换礼品: " + gift.getName());
        tx.setCreatedAt(LocalDateTime.now());
        pointsTransactionMapper.insert(tx);

        // create redemption record
        GiftRedemption redemption = new GiftRedemption();
        redemption.setUserId(user.getId());
        redemption.setGiftId(giftId);
        redemption.setStatus("PENDING");
        redemption.setCreatedAt(LocalDateTime.now());
        giftRedemptionMapper.insert(redemption);

        // reduce stock in catalog
        gift.setStock(Math.max(0, gift.getStock() - 1));
        giftMapper.update(gift);

        return "redirect:/points";
    }
}